<style scoped src="./index.scss" lang="scss" rel="stylesheet/scss"></style>
<template src="./index.html"></template>
<script>

export default {
    mixins: [Vue.prototype.$vFN.Mixins.Base, Vue.prototype.$vFN.Mixins.Edit],
    components: {
        SelectDataGoods: async () =>
            Vue.extend(await Vue.prototype.$vFN.Components.Base.SelectDataGoods()),
        SelectDataCoupon: async () =>
            Vue.extend(await Vue.prototype.$vFN.Components.Base.SelectDataCoupon()),
            
    },
    data() {
        return {
            appWindow: window,
            form: {
                // 商品id
                products_id: 1,
                // 活动对象 1：全部会员，2：会员等级，3：会员标签
                active_object: 1,
                // 团购活动描述
                active_describe: "",
                // 团购标题
                title: "",
                // 团购开始时间， 小于当前时间则直接开启
                start_time: "",
                // 团购结束时间
                end_time: "",
                // 当参团人数达到多少时开团按钮不显示（移动端商品详情页底部仅展示“去参团”，不展示“一键开团）,0:无限制
                hide_number: null,
                // 0:正常拼团 1：老拉新
                active_module: 0,
                // 购买须知
                note: "",
                // 每人最多参与几次不同的团（拼团设置）0:无限制
                join_number: null,
                active_level: [
                    {level_number: 1, member_number: null, active_time: ""}
                ],
                
                sku: [],

                team_leader_award: [],
                value: [],
                // lottery: {
                //     // 是否开启抽奖，0：关闭，1开启
                //     is_open: 1,
                //     // 是否应用独立规则，0：应用，1不应用
                //     is_separate_rules: 0,
                //     // 团长抽奖设置，0：无限制，1：必中，2：必不中
                //     team_leader_set: 0,
                //     // 新成员抽奖设置，0：无限制，1：必中，2：必不中
                //     team_new_member_set	: 0,
                //     // 中奖奖励
                //     winning_reward: {
                //         // 爱心值
                //         love: "",
                //         // 余额
                //         balance: "",
                //         // 积分
                //         integral: "",
                //         // 优惠卷ID，逗号分割开
                //         coupon: [],
                //     },
                //     // 未中奖补偿
                //     loser_reward: {
                //         // 爱心值
                //         love: "",
                //         // 余额
                //         balance: "",
                //         // 积分
                //         integral: "",
                //         // 优惠卷ID，逗号分割开
                //         coupon: [],
                //     }
                // }

            },
            team_leader_list: [],

            // 页面接口地址
            apiUrl: {
                create: "admin/active/publish",
                update: "admin/active/editActive",
                detail: "admin/active/activeDetail",
            },
            goodsIds: [],

            levels: [],
            // 判断上一步下一步操作
            next_type: 0,

            product: [],

            couponsIds: []

        };
    },
    methods: {
        async selectCoupon() {
            this.$vFN.Directives.SelectDataCoupons({
                // count: 1,
                appWindow: this.appWindow,
                clientType: "platform",
                couponsIds: this.couponsIds,
                apiConfig: this.$vFN.Tools.getAppGlobalData('componentsApiConfig.SelectDataCoupons', this.appWindow),
                onSuccess: (ids) => {
                    this.form.team_leader_award.forEach(item => {
                        // console.log(item);
                        if(item.type == 'select') {
                            item.award = ids;
                            this.couponsIds = ids;
                        }
                    });
                }
            })
        },
        getAward() {
            this.form.team_leader_award.forEach(item => {
                if(item.type == 'select') {
                    console.log(item.award);
                    item.award = this.couponsIds;
                }
            });
        },

        // 团长福利
        async getData() {
            let res = await this.$vFN.Http.post({
                url: "admin/active/teamCanSelect",
            }, window);
            // console.log(res.data);
            this.form.team_leader_award = res.data
        },
        // 上一步
        lastStep() {
            this.next_type --;
        },
        // 下一步
        async nextStep(params_) {
            // 表单规则验证
            let _isValidate = await this.mixinEdit_formValidate(params_.ref);
            if (!_isValidate) {
                return;
            }

            if(this.goodsIds.length <= 0) {
                this.$vFN.Tools.messageError("请选择活动商品");
                return;
            }
            this.form.products_id = this.goodsIds[0];
            
            let isTime = this.form.active_level.every(item => {
                if(item.member_number == "" || item.member_number == null || item.member_number == 1) {
                    this.$vFN.Tools.messageError("拼团人数不能为空且不能小于1");
                    return false;
                }else if(item.active_time == "" || item.active_time == null) {
                    this.$vFN.Tools.messageError("拼团时间不能为空");
                    return false;
                }else {
                    return true
                }
            });
            // console.log(isTime);
            if(!isTime) {
                return;
            }

            this.next_type ++;
            // 编辑不用再次调用，防止数据被覆盖
            if(this.mixinEdit_editType != 'update') {
                this.getSku();
            }
        },
        // form 提交添加/修改 的参数扩展方法
        mixinEdit_editFormSubmitExtend(data_) {
            data_.active_level.forEach(item => {
                if(typeof item.active_time == "number") {
                    item.active_time = JSON.stringify(item.active_time)
                }
            });

            data_.team_leader_award.forEach(item => {
                if(item.type == 'select') {
                    item.award = this.couponsIds;
                }
            })

            data_.start_time = this.$vFN.Utils.timestampToDate("yyyy-MM-dd HH:mm", data_.value[0]);
            data_.end_time = this.$vFN.Utils.timestampToDate("yyyy-MM-dd HH:mm", data_.value[1]);
            return data_;
        },
        // 编辑修改的参数扩展方法
        mixinEdit_editDataExtend(data_) {
            // 添加
            if (this.mixinEdit_editType == "add") {
                this.getData();
            }
            // 修改
            else if (this.mixinEdit_editType == "update") {
                this.goodsIds = [data_.products_id];
                data_.value = [data_.start_time, data_.end_time]

                data_.team_leader_award.forEach(item => {
                    if(item.type == 'select') {
                        this.couponsIds = item.award
                    }
                })
            }
            // 复制
            else if (this.mixinEdit_editType == "copy") {

            }

            return data_;
        },
        // 添加拼团层级
        addLevel() {
            if(this.form.active_level.length == 3) {
                this.$vFN.Tools.messageError("最多可设置3个拼团层级");
                return;
            }
            let _f = {
                level_number: this.form.active_level.length + 1,
                member_number: null,
                active_time: "",
            }
            this.form.active_level.push(_f);
            this.addSkuLevel();
        },
        // 删除拼团层级
        delLevel(item, index) {
            this.$delete(this.form.active_level, index);
            this.addSkuLevel();
        },
        // 获取规格
        async getSku() {
            let res = await this.$vFN.Http.post({
                domain: "APP_MAIN_DOMAIN",
                url: "mall-site-portal/product/getItem",
                data: {
                    id: this.goodsIds[0],
                }
            }, window);
            
            // 添加商品时规格库存显示
            this.product = res.data.skuStockLst;

            let _k;
            this.form.sku = [];
            res.data.skuStockLst.forEach((item, index) => {
                _k = {
                    product_sku_id: item.id,
                    buy_limit: 0,
                    level: JSON.parse(JSON.stringify(this.levels)),
                }
                this.form.sku.push(_k);
                
            });
            
        },
        // 拼团价格
        async addSkuLevel() {
            let _list = this.form.active_level;
            let _e;
            this.levels = [];
            _list.forEach((item, index) => {
                _e = {
                    level_number: index + 1,
                    active_price: "",
                }
                this.levels.push(_e);
            });
            // console.log(this.levels);
            this.form.sku.forEach(item => {
                item.level = this.levels
            });
        },

        // 初始化
        async init() {
            this.addSkuLevel();
            // 初始化数据
            await this.mixinEdit_editBoxInit({
                model: "form",
                id: this.id,
            });
        },

    },
    mounted() {
        this.init();
    },
    activated() {},
};
</script>